import 'dart:developer';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_html_table/flutter_html_table.dart';
import 'package:get/get.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/picture_preview_widget.dart';

class HelpHtml extends StatelessWidget {
  const HelpHtml({super.key, required this.content});

  final String content;

  @override
  Widget build(BuildContext context) {
    return Html(
      shrinkWrap: true,
      data: getData(),
      extensions: [
        TableHtmlExtension(),
        TagExtension(
            tagsToExtend: {"img"},
            builder: (extensionContext) {
              final e = extensionContext.styledElement;
              return GestureDetector(
                onTap: () => Get.dialog(
                    PicturePreview(imageUrl: e?.attributes['src'] ?? ""),
                    useSafeArea: false),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: CachedNetworkImage(
                    imageUrl: e?.attributes['src'] ?? "",
                    width: Get.width,
                    fit: BoxFit.cover,
                    placeholder: (context, url) => Container(),
                    errorWidget: (context, url, error) => Container(),
                  ),
                ),
              );
            }),
      ],
      onLinkTap: (url, context, element) => Utils.doJump(url ?? ""),
      style: {
        "body": Style(
            letterSpacing: -0.5,
            margin: Margins.only(left: 16, right: 16, top: 8)),
        "p": Style(
            margin: Margins.all(0),
            textAlign: TextAlign.justify,
            fontSize: FontSize(15),
            lineHeight: const LineHeight(1.6),
            color: Colours.text44),
        "a": Style(
            color: Colours.blue2766D6, textDecoration: TextDecoration.none),
        "img": Style(
            // width: Width(Get.width - 32),
            margin: Margins.zero,
            padding: HtmlPaddings.zero,
            display: Display.block,
            textAlign: TextAlign.center),
      },
    );
  }

  String getData() {
    var regC = RegExp(r"[\u4e00-\u9fa5]");
    var regCom = RegExp(r'<\/p>[.\n\s]*<p>');
    var regP = RegExp(r'\/>[.\n\s]*<p>');
    var regImg = RegExp(r'\/>[.\n\s]*<img');
    var regInLine = RegExp(r'<p[^<>]*>[^<>]+<img');
    String append = '';
    String com = content.splitMapJoin(regInLine, onMatch: (match) {
      var result = match[0]?.split("<img").join("</p><p><img") ?? "";
      return result;
    });
    // .split(RegExp(r"<[br \/]+>")).join("")
    com = com.replaceAllMapped(
        RegExp(r"<div\s.*?>([\s\S]*?)<\/div>"), (match) => match.group(1)!);
    com = com.replaceAllMapped(RegExp(r"""<span class="img">(.*?)<\/span>"""),
        (match) => match.group(1)!);
    com = com
        .split("<p>&nbsp;</p>")
        .join("<div style= 'height: 12;width: 200px;'>  </div>")
        .split(regCom)
        .join("</p><div style= 'height: 12;width: 200px;'>  </div><p>")
        .split(regP)
        .join("/><div style= 'height: 12;width: 200px;'>  </div><p>")
        .split(regImg)
        .join("/><div style= 'height: 12;width: 200px;'>  </div><img")
        .split('src=" ')
        .join('src="');
    // .split(regBody)
    // .join("/p><div style= 'height: 25;width: 200px;'>  </div></body");
    log(com);
    com.split("").forEach((element) {
      if (regC.hasMatch(element)) {
        append += "$element\u200A";
      } else {
        append += element;
      }
    });

    var newData = "";
    newData = "<body id='wholeBody'>"
        "<div id='article'>$append</div>"
        "<div style= 'height: 24px;width: 200px;'>  </div>"
        "</body>";
    return newData;
  }
}
